package com.zyw.boot.tool;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class FileTranslatorBaidu {

    // 百度翻译API的密钥
    private static final String APP_ID = "APP_ID";
    private static final String SECRET_KEY = "SECRET_KEY";

    static String SOURCE_DIR = "SOURCE_DIR";
    static String TARGET_DIR = "TARGET_DIR";

    public static void main(String[] args) {
        try {
            File targetDir = new File(TARGET_DIR);
            if (!targetDir.exists()) targetDir.mkdirs();

            File[] files = new File(SOURCE_DIR).listFiles();
            if (files == null) {
                System.out.println("没有找到文件");
                return;
            }

            for (File file : files) {
                if (file.isFile()) {
                    processFile(file, targetDir);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void processFile(File file, File targetDir) {
        try {
            // 读取文件内容（使用UTF-8编码）
            String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);

            // 调用翻译API
            String translated = translate(content);

            // 生成新文件名
            String newName = generateNewName(file.getName());
            File outputFile = new File(targetDir, newName);

            // 写入翻译结果（UTF-8编码）
            Files.write(outputFile.toPath(), translated.getBytes(StandardCharsets.UTF_8));
            System.out.println("文件已翻译保存至：" + outputFile);
        } catch (Exception e) {
            System.err.println("处理文件失败：" + file.getName());
            e.printStackTrace();
        }
    }

    private static String generateNewName(String original) {
        int dotIndex = original.lastIndexOf('.');
        if (dotIndex > 0) {
            return original.substring(0, dotIndex) + "_chinese" + original.substring(dotIndex);
        }
        return original + "_chinese";
    }

    private static String translate(String query) throws Exception {
        String url = "https://fanyi-api.baidu.com/api/trans/vip/translate";
        int salt = new Random().nextInt(10000);
        String sign = md5(APP_ID + query + salt + SECRET_KEY);

        // 构建请求参数
        String params = "q=" + URLEncoder.encode(query, "UTF-8")
                + "&from=auto&to=zh"
                + "&appid=" + APP_ID
                + "&salt=" + salt
                + "&sign=" + sign;

        // 发送POST请求
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        try (OutputStream os = conn.getOutputStream()) {
            os.write(params.getBytes(StandardCharsets.UTF_8));
        }

        // 读取响应
        if (conn.getResponseCode() != 200) {
            throw new IOException("API请求失败: " + conn.getResponseMessage());
        }

        String jsonResponse;
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            jsonResponse = String.join("", reader.lines().toArray(String[]::new));
        }

        // 解析JSON结果
        JSONObject json = new JSONObject(jsonResponse);
        if (json.has("error_code")) {
            throw new IOException("翻译错误: " + json.getString("error_msg"));
        }

        // 拼接翻译结果
        JSONArray results = json.getJSONArray("trans_result");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < results.length(); i++) {
            sb.append(results.getJSONObject(i).getString("dst"));
            sb.append("\n\n");

        }
        return sb.toString();
    }

    private static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte b : hash) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不可用", e);
        }
    }
}